const layerService = require('../services/layerService');
const { success, successWithData, error } = require('../utils/resultwrapper');

class LayerController {
  /**
   * 获取图层列表
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  async getLayerList(req, res) {
    try {
      const result = await layerService.getLayerList(req.query);
      res.json(successWithData(result));
    } catch (err) {
      error(err.message);
    }
  }

  /**
   * 获取图层详情
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  async getLayerById(req, res) {
    try {
      const result = await layerService.getLayerById(req.params.id);
      if (!result) {
        return error('图层不存在');
      }
      res.json(successWithData(result));
    } catch (err) {
      error(err.message);
    }
  }

  /**
   * 创建图层
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  async createLayer(req, res) {
    try {
      const result = await layerService.createLayer({
        ...req.body,
        createBy: req.user.userName
      });
      res.json(successWithData(result));
    } catch (err) {
      error(err.message);
    }
  }

  /**
   * 更新图层
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  async updateLayer(req, res) {
    try {
      const result = await layerService.updateLayer(req.params.id, {
        ...req.body,
        updateBy: req.user.userName
      });
      res.json(successWithData(result));
    } catch (err) {
      error(err.message);
    }
  }

  /**
   * 删除图层
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  async deleteLayer(req, res) {
    try {
      const result = await layerService.deleteLayer(req.params.id);
      if (!result) {
        return error('删除失败');
      }
      res.json(success());
    } catch (err) {
      error(err.message);
    }
  }

  /**
   * 获取菜单下的图层列表
   * @param {Object} req 请求对象
   * @param {Object} res 响应对象
   */
  async getLayersByMenuId(req, res) {
    try {
      const result = await layerService.getLayersByMenuId(req.params.menuId);
      res.json(successWithData(result));
    } catch (err) {
      error(err.message);
    }
  }
}

module.exports = new LayerController(); 